<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/3/28
 * Time: 17:02
 */

namespace iBrand\Shop\Server\Resources;

use iBrand\Common\Resources\BaseResource;
//use iBrand\Component\Discount\Services\DiscountService;
use iBrand\Shop\Core\Models\ShopBrandRelation;
use iBrand\Shop\Server\Service\DiscountService;
use Illuminate\Support\Collection;

class O2oGoodsResource extends BaseResource
{
    public function toArray($request)
    {
        $this->resource->can_change_discount = true;  //是否可在前端修改折扣
        $percentage = 100;
        /*品牌折扣*/
        $this->resource->user_discount = 100;


        $brand_id = $this->resource->baseGoods->brand_id;

        if ($shopBrand = ShopBrandRelation::where('brand_id', $brand_id)->where('shop_id', $this->resource->shop_id)->first()
            AND !$this->resource->baseGoods->is_discount) {  //正常的品牌折扣
            $percentage = $shopBrand->discount;
            $this->resource->user_discount = $shopBrand->discount;

        }

        //清仓折扣
        $clearDiscounts = app(DiscountService::class)->getDiscountsByGoods($this->resource->baseGoods, 'shop', 1);
        $clearDiscount = $clearDiscounts->filter(function ($discount) {
            return $discount->coupon_based == 0;
        })->first();
        if ($clearDiscount) {
            $action = $clearDiscount->actions->filter(function ($action) {
                return $action->type == 'goods_percentage_discount';
            })->first();
            if ($action) {
                $percentage = json_decode($action->configuration, true)['percentage'];
                $this->resource->user_discount = $percentage;
            }
        }

        if ($this->resource->O2oGoods->is_discount) {  //如果设置为一口价商品，会员折扣为100%
            $percentage = 100;
            $this->resource->user_discount = $percentage;
            $this->resource->can_change_discount = false;  //如果是特价商品，不可修改折扣
        }

        $this->resource->discount_price = number_format($this->resource->baseGoods->sell_price * ($percentage / 100), 2, ".", "");;  //折后价

        /*是否可使用积分抵扣*/
        $point_deduction = 0;
        if (!settings($this->resource->shop_id.'_shop_point_disable')) {
            $point_deduction = $this->resource->O2oGoods->point_deduction;
        }

        $this->resource->point_deduction = $point_deduction;


        /*获取改商品参与的促销活动ID*/
        $discounts = app(DiscountService::class)->getDiscountsByGoods($this->resource->baseGoods);
        $discounts = $discounts->filter(function ($discount) {
            return $discount->coupon_based == 0;
        });
        $discountIds = [];
        if ($discounts->count() > 0) {
            $discountIds = $discounts->pluck('id')->toArray();
        }
        $this->resource->discount_ids = $discountIds;


        return parent::toArray($request);
    }
}